
import React from 'react';
import {Form, Input, Button, Spin, Tooltip} from 'antd';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {fetchData, receiveData} from '@/action';
import * as images from '../../style/imgs';

import {REQUEST_SUCCESS} from '../../common/const';

const FormItem = Form.Item;
let isCapsLock = undefined; //大写键盘是否开启

class Login extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loginTip: null,
            loading: false,
            title: '大小写锁定已打开',
            visible: false
        };
    }


    componentWillMount() {
        //已登录的用户再次进入登录页面自动跳转主页
        if (localStorage.getItem('user')) {
            //60分钟内无操作判断回话过期
            const current = new Date().getTime();
            const diff = current - Number(localStorage.getItem('last'));
            if(diff/1000 < 3600){
                this.props.history.push('/app/homepage');
            }
            return;
        }
        const {receiveData} = this.props;
        receiveData(null, 'auth');
    }

    componentWillUnmount() {
        this.setState = () => {
            return;
        }
    }

    componentDidMount() {
        window.addEventListener('keyup', (event) => {
            if (event.target.type !== 'password') return;
            const keyCode = event.keyCode;
            if (keyCode >= 65 && keyCode <= 90) {
                isCapsLock = this.isCapsLock(event);
            } else if (event.key == 'CapsLock') {
                (isCapsLock !== undefined) && (isCapsLock = !isCapsLock);
            }
            this.setState({
                visible: isCapsLock !== undefined ? isCapsLock : false
            });
        });
    }

    componentDidUpdate(prevProps) { // React 16.3+弃用componentWillReceiveProps
        const {auth: nextAuth = {}, history} = this.props;
        if (nextAuth.data && nextAuth.data.code == REQUEST_SUCCESS) {   // 判断是否登陆
            if (!localStorage.getItem('user')) {
                const permission = this.getPermission(nextAuth.data.data.permissionList);
                localStorage.setItem('user', JSON.stringify({permission: permission, ...nextAuth.data.data.user}));
                localStorage.removeItem('logout');
            }
            history.push('/');
        }
    }

    isCapsLock = (e) => {
        const key = e.key;
        const keyCode = key.charCodeAt(0);
        const shifKey = e.shiftKey;
        return (keyCode >= 65 && keyCode <= 90 && !shifKey) || (keyCode >= 97 && keyCode <= 122 && shifKey);
    }
    hasErrors = (fieldsError) => {
        const value = this.props.form.getFieldsValue();
        return !Object.keys(value).every(field => value[field]) ||
            Object.keys(fieldsError).some(field => fieldsError[field]);
    }
    getPermission = (data, permission = []) => {
        data.map(item => {
            permission.push(item.permission);
        });
        return permission;
    }

    fieldChange = () => {
        this.setState({
            loginTip: null
        });
    }

    handleSubmit = (e) => {
        e.preventDefault();
        const _this = this;
        const qs = require('qs');
        const {fetchData} = _this.props
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.setState({loading: true});
                fetchData({funcName: 'login', params: qs.stringify(values), stateName: 'auth'}).then(res => {
                    let data = res && res.data;
                    if ( data && REQUEST_SUCCESS !== data.code) {
                        _this.setState({
                            loginTip: data.msg
                        });
                    }
                    this.setState({
                        loading: false
                    })
                })
            }
        });
    };

    render() {
        const {getFieldDecorator, getFieldsError} = this.props.form;
        return (
            <div className="login" style={{backgroundColor: 'white'}}>
                <Spin spinning={this.state.loading}>
                    <div className="login-form" style={{boxShadow: "none"}}>
                        <div className="login-logo" style={{height: 'auto'}}>
                            <img src={images['logo']} alt={''}/>
                            <p style={{
                                fontFamily: '"微软雅黑 Bold", "微软雅黑"',
                                fontSize: 18,
                                fontWeight: 700,
                                fontStyle: 'normal',
                                color: '#999999'
                            }}>WPS 升级服务器管理后台</p>
                        </div>
                        <Form onSubmit={this.handleSubmit} style={{maxWidth: '300px'}}>
                            <FormItem>
                                {getFieldDecorator('username', {
                                    rules: [{required: true, message: '请输入用户名!'}],
                                })(
                                    <Input placeholder="用户名" onChange={this.fieldChange} maxLength={255}/>
                                )}
                            </FormItem>
                            <FormItem>
                                <Tooltip placement={'right'} title={this.state.title} visible={this.state.visible}
                                         arrowPointAtCenter={true}>
                                    {getFieldDecorator('password', {
                                        rules: [{required: true, message: '请输入密码!'}],
                                    })(
                                        <Input type="password" placeholder="密码" onChange={this.fieldChange}
                                               maxLength={255}/>
                                    )}
                                </Tooltip>
                            </FormItem>
                            <FormItem>
                                {/*<a className="login-form-forgot" href="" style={{float: 'right'}}>修改密码</a>*/}
                                <span style={{
                                    color: 'red',
                                    height: 40,
                                    display: 'block'
                                }}>{this.state.loginTip || ''}</span>
                                <Button type="primary" htmlType="submit" className="login-form-button"
                                        style={{width: '100%'}}
                                        disabled={this.hasErrors(getFieldsError())}
                                >
                                    登录
                                </Button>
                            </FormItem>
                        </Form>
                    </div>
                </Spin>
                <style>{`
                    .ant-tooltip-inner{
                    background-color:white;
                    color:black;
                    }
                    .ant-tooltip-placement-right .ant-tooltip-arrow{
                        border-right-color:white;
                    }
                `}</style>
            </div>

        );
    }
}

const mapStateToPorps = state => {
    const {auth} = state.httpData;
    return {auth};
};
const mapDispatchToProps = dispatch => ({
    fetchData: bindActionCreators(fetchData, dispatch),
    receiveData: bindActionCreators(receiveData, dispatch)
});


export default connect(mapStateToPorps, mapDispatchToProps)(Form.create()(Login));